package com.witmob.drivers;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.witmob.drivers.data.DriverContentProvider;
import com.witmob.drivers.model.VehiclesInfo;
import com.witmob.drivers.model.Weather;
import com.witmob.drivers.util.DataUtil;
import com.witmob.drivers.util.DefultUtil;
import com.witmob.drivers.util.Global;
import com.witmob.drivers.weather.Forecast_conditions;
import com.witmob.drivers.weather.ReadWeather;

public class NewMainActivity extends Activity {
    /** Called when the activity is first created. */
	
	static final int FLING_MIN_DISTANCE = 80, FLING_MIN_VELOCITY = 200;
	static final int WEATHER_GET_DATA_SUC = 200, WEATHER_GET_DATA_FAILURE = 500;
	//城市
	private String cityName = "北京";
	//三天的天气View
	View todayView, acquiredView, tomorrowView;
	//滑动的天气ViewGroup
	private ViewFlipper viewFlipper;
	//分页ViewGroup
	private LinearLayout pagecontrl_layout;
	//分页的页码   第一页    总页数    当前页
	private int initialPageNum, allPageNum, currentPageNum;
	//汽车视图ViewGroup
	LinearLayout car_info_layout;
	//违章车辆list
	List<VehiclesInfo> vehiclesInfos = new ArrayList<VehiclesInfo>();
	
	private Weather weather = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        initView();
    }
    
    @Override
    protected void onStart() {
    	super.onStart();
    	if(weather == null){
    		refresh();
    	}
    }
    
    private void initView(){
    	viewFlipper = (ViewFlipper) findViewById(R.id.weather_filpper);
        
        pagecontrl_layout = (LinearLayout) findViewById(R.id.pagecontrl_layout);
        //设置天气视图。
        setViewFlipperView();
        
        car_info_layout = (LinearLayout) findViewById(R.id.car_info_layout);
        setCarInfoView();
    }
    
    //得到天气数据
	private int setWeatherData(){
		ReadWeather readWeather = new ReadWeather();
		weather = readWeather
				.analysisData(readWeather
						.downData(Global.GOOGLE_URL_WEATHER+cityName));
		if(weather != null){
			return WEATHER_GET_DATA_SUC;
		} else {
			return WEATHER_GET_DATA_FAILURE;
		}
	}
	
	private void setWeatherDataInView(Weather weather){
		Log.v(Global.TAG, ""+weather);
		weather = DataUtil.getAllWeatherInfo(weather);
		
		Log.i(Global.TAG, ""+weather.getForecast_information().getCity().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getPostal_code().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getLatitude_e6().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getLongitude_e6().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getForecast_data().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getCurrent_data_time().getData());
		Log.i(Global.TAG, ""+weather.getForecast_information().getUnit_system().getData());
		Log.i(Global.TAG, "------------------------------------------------------");
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getCondition().getData());
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getTemp_f().getData());
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getTemp_c().getData());
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getHumidity().getData());
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getIcon().getData());
		Log.i(Global.TAG, ""+weather.getCurrent_conditions().getWind_condition().getData());
		Log.i(Global.TAG, "------------------------------------------------------");
		for(Forecast_conditions forecast_conditions : weather.getForecast_conditionses()){
			Log.i(Global.TAG, ""+forecast_conditions.getDay_of_week().getData());
			Log.i(Global.TAG, ""+forecast_conditions.getLow().getData());
			Log.i(Global.TAG, ""+forecast_conditions.getHigh().getData());
			Log.i(Global.TAG, ""+forecast_conditions.getIcon().getData());
			Log.i(Global.TAG, ""+forecast_conditions.getCondition().getData());
			Log.i(Global.TAG, "------------------------------------------------------");
		}
		Log.i(Global.TAG, "------------------------------------------------------");
		Log.i(Global.TAG, ""+weather.getPhoto());
		
		((TextView) todayView.findViewById(R.id.area)).setText(cityName);
		((TextView) todayView.findViewById(R.id.mouth)).setText(weather.getForecast_conditionses().get(0).getDay());
		((TextView) todayView.findViewById(R.id.week)).setText(weather.getForecast_conditionses().get(0).getDay_of_week().getData());
		((TextView) todayView.findViewById(R.id.weather_display)).setText(weather.getForecast_conditionses().get(0).getCondition().getData());
		((TextView) todayView.findViewById(R.id.temperature)).setText(weather.getForecast_conditionses().get(0).getLow().getData()+"~"+weather.getForecast_conditionses().get(0).getHigh().getData()+"℃");
		Drawable drawable = DataUtil.setWeartherDrawable(this, weather.getForecast_conditionses().get(0).getIcon().getData());
		((ImageView) todayView.findViewById(R.id.weather_image)).setImageDrawable(drawable);
		
		((TextView) tomorrowView.findViewById(R.id.area)).setText(cityName);
		((TextView) tomorrowView.findViewById(R.id.mouth)).setText(weather.getForecast_conditionses().get(1).getDay());
		((TextView) tomorrowView.findViewById(R.id.week)).setText(weather.getForecast_conditionses().get(1).getDay_of_week().getData());
		((TextView) tomorrowView.findViewById(R.id.weather_display)).setText(weather.getForecast_conditionses().get(1).getCondition().getData());
		((TextView) tomorrowView.findViewById(R.id.temperature)).setText(weather.getForecast_conditionses().get(1).getLow().getData()+"~"+weather.getForecast_conditionses().get(1).getHigh().getData()+"℃");
		drawable = DataUtil.setWeartherDrawable(this, weather.getForecast_conditionses().get(1).getIcon().getData());
		((ImageView) tomorrowView.findViewById(R.id.weather_image)).setImageDrawable(drawable);
		
		((TextView) acquiredView.findViewById(R.id.area)).setText(cityName);
		((TextView) acquiredView.findViewById(R.id.mouth)).setText(weather.getForecast_conditionses().get(2).getDay());
		((TextView) acquiredView.findViewById(R.id.week)).setText(weather.getForecast_conditionses().get(2).getDay_of_week().getData());
		((TextView) acquiredView.findViewById(R.id.weather_display)).setText(weather.getForecast_conditionses().get(2).getCondition().getData());
		((TextView) acquiredView.findViewById(R.id.temperature)).setText(weather.getForecast_conditionses().get(2).getLow().getData()+"~"+weather.getForecast_conditionses().get(2).getHigh().getData()+"℃");
		drawable = DataUtil.setWeartherDrawable(this, weather.getForecast_conditionses().get(2).getIcon().getData());
		((ImageView) acquiredView.findViewById(R.id.weather_image)).setImageDrawable(drawable);
		
		washSuggestion(weather);
		setProgressBarVisible(false);
	}
	
	//洗车建议数据显示
	private void washSuggestion(Weather weather){
		boolean b0,b1,b2,b3;
		b0 = weather.getForecast_conditionses().get(0).getCondition().getData().equals("雨");
		b1 = weather.getForecast_conditionses().get(1).getCondition().getData().equals("雨");
		b2 = weather.getForecast_conditionses().get(2).getCondition().getData().equals("雨");
		b3 = weather.getForecast_conditionses().get(3).getCondition().getData().equals("雨");
		
		if(!b0){
			if(!b1){
				if(!b2){
					((TextView) todayView.findViewById(R.id.weather_forThings)).setText(R.string.suitable_for_car_wash);
					((TextView) todayView.findViewById(R.id.weather_forThings_detail)).setText(R.string.suitable_for_car_wash_detail);
				} else {
					((TextView) todayView.findViewById(R.id.weather_forThings)).setText(R.string.more_appropriate_for_the_car_wash);
					((TextView) todayView.findViewById(R.id.weather_forThings_detail)).setText(R.string.more_appropriate_for_the_car_wash_detail);
				}
			} else {
				((TextView) todayView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
				((TextView) todayView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing2_detail);
			}
		} else {
			((TextView) todayView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
			((TextView) todayView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing_detail);
		}
		if(!b1){
			if(!b2){
				if(!b3){
					((TextView) tomorrowView.findViewById(R.id.weather_forThings)).setText(R.string.suitable_for_car_wash);
					((TextView) tomorrowView.findViewById(R.id.weather_forThings_detail)).setText(R.string.suitable_for_car_wash_detail);
				} else {
					((TextView) tomorrowView.findViewById(R.id.weather_forThings)).setText(R.string.more_appropriate_for_the_car_wash);
					((TextView) tomorrowView.findViewById(R.id.weather_forThings_detail)).setText(R.string.more_appropriate_for_the_car_wash_detail);
				}
			} else {
				((TextView) tomorrowView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
				((TextView) tomorrowView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing2_detail);
			}
		} else {
			((TextView) tomorrowView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
			((TextView) tomorrowView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing_detail);
		}
		if(!b2){
			if(!b3){
				((TextView) acquiredView.findViewById(R.id.weather_forThings)).setText(R.string.more_appropriate_for_the_car_wash);
				((TextView) acquiredView.findViewById(R.id.weather_forThings_detail)).setText(R.string.more_appropriate_for_the_car_wash_detail);
			} else {
				((TextView) acquiredView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
				((TextView) acquiredView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing2_detail);
			}
		} else {
			((TextView) acquiredView.findViewById(R.id.weather_forThings)).setText(R.string.not_washing);
			((TextView) acquiredView.findViewById(R.id.weather_forThings_detail)).setText(R.string.not_washing_detail);
		}
		
	}
    
    //设置天气的三个视图，默认显示第一个
    private void setViewFlipperView(){
    	viewFlipper.removeAllViews();
    	todayView = getLayoutInflater().inflate(R.layout.weather_info, null);
    	tomorrowView = getLayoutInflater().inflate(R.layout.weather_info, null);
    	acquiredView = getLayoutInflater().inflate(R.layout.weather_info, null);
    	viewFlipper.addView(todayView);
    	viewFlipper.addView(tomorrowView);
    	viewFlipper.addView(acquiredView);
    	
        initialPageNum = 0; //初始显示的页数
		allPageNum = 3;  //视图总数
		currentPageNum = initialPageNum; //当前显示的第几页
        this.viewFlipper.setOnTouchListener(dragt);
        DefultUtil.setProgressBar(pagecontrl_layout, initialPageNum, allPageNum,
        		NewMainActivity.this);
        
    }
    
    OnTouchListener dragt = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
				case MotionEvent.ACTION_MOVE: {
					gestureDetector2.onTouchEvent(event);
					break;
				}// inner case MOVE
				case MotionEvent.ACTION_UP: {
					gestureDetector2.onTouchEvent(event);
					return true;
				}// inner case UP
				case MotionEvent.ACTION_DOWN: {
					gestureDetector2.onTouchEvent(event);
					break;
				}// inner case UP
	
				default:
					break;
			}
			return true;
		}
	};
	//控制viewFillper的手势事件
	private GestureDetector gestureDetector2 = new GestureDetector(new OnGestureListener() {
		
		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			Log.i("cat", "onSingleTapUp  flipper");
			return false;
		}
		@Override
		public void onShowPress(MotionEvent e) {
			Log.i("cat", "onShowPress  flipper");
		}
		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
			return false;
		}
		@Override
		public void onLongPress(MotionEvent e) {
			Log.i("cat", "onLongPress  flipper");
		}
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE) {
				Log.v("cat", "@@@@@@@@@@@1");
				if ((currentPageNum ) >= (allPageNum - 1)) {
					currentPageNum = allPageNum - 1;
					Log.v("cat", "@@@@@@@@@@@2");
				} else {
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(NewMainActivity.this, R.anim.push_left_in));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(NewMainActivity.this,R.anim.push_left_out));
					viewFlipper.showNext();
					currentPageNum = currentPageNum + 1;
					DefultUtil.setProgressBar(pagecontrl_layout, currentPageNum, allPageNum, NewMainActivity.this);
					Log.v("cat", "@@@@@@@@@@@3");
				}
				return true;
			} else if (e1.getX() - e2.getX() < -FLING_MIN_DISTANCE) {
				Log.v("cat", "@@@@@@@@@@@4");
				if (currentPageNum - 1 < 0) {
					currentPageNum = initialPageNum;
					DefultUtil.setProgressBar(pagecontrl_layout, currentPageNum, allPageNum, NewMainActivity.this);
					Log.v("cat", "@@@@@@@@@@@5");
				} else {
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(NewMainActivity.this, R.anim.push_right_in));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(NewMainActivity.this, R.anim.push_right_out));
					viewFlipper.showPrevious();
					currentPageNum = currentPageNum - 1;
					DefultUtil.setProgressBar(pagecontrl_layout, currentPageNum, allPageNum, NewMainActivity.this);
					Log.v("cat", "@@@@@@@@@@@6");
				}
				return true;
			} 
			Log.v("cat", "@@@@@@@@@@@7");
			return false;
		}
		@Override
		public boolean onDown(MotionEvent e) {
			Log.v("cat", "!!!!!!!!!!!!!!");
			return true;
		}
	});
	
	//设置汽车信息视图。
    private void setCarInfoView(){
    	getCarinfos();
    	for(int i=0;i<vehiclesInfos.size();i++){
    		VehiclesInfo versionInfo = vehiclesInfos.get(i);
    		View carView = getLayoutInflater().inflate(R.layout.car_info, null);
    		
    		TextView numberPlate = (TextView) carView.findViewById(R.id.numberPlate);
    		numberPlate.setText(versionInfo.getCarLicense());
    		Log.v(Global.TAG, ""+versionInfo.getImageId());
    		LinearLayout.LayoutParams localLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
			localLayoutParams.leftMargin = 10;
			localLayoutParams.topMargin = 10;
			localLayoutParams.rightMargin = 10;
			localLayoutParams.bottomMargin = 10;
        	car_info_layout.addView(carView, localLayoutParams);
    	}
    }
    
    private void getCarinfos(){
    	vehiclesInfos.clear();
		Cursor cursor = managedQuery(DriverContentProvider.CONTENT_URI, null,
				null, null, null);
		
		while (cursor.moveToNext()) {
			VehiclesInfo vehiclesInfo = new VehiclesInfo();
			vehiclesInfo.setId(cursor.getInt(0));
			vehiclesInfo.setCarLicense(cursor.getString(1));
			vehiclesInfo.setEngineModel(cursor.getString(2));
			vehiclesInfo.setImageId(cursor.getInt(3));
			vehiclesInfos.add(vehiclesInfo);
		}
		cursor.close();
    }
    //刷新
    private void refresh(){
    	setProgressBarVisible(true);
    	new Thread(new Runnable() {
			@Override
			public void run() {
				weatherHandler.sendEmptyMessage(setWeatherData());
			}
		}).start();
    }

    private Handler weatherHandler = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		switch (msg.what){
    			case WEATHER_GET_DATA_SUC:
    				setWeatherDataInView(weather);
    				
    				break;
    			case WEATHER_GET_DATA_FAILURE:
    				//TODO 增加访问网络失败的视图
    				break;
    				
    			default:
    				break;
    		}
    	};
    };
    
    private void setProgressBarVisible(boolean bl){
    	todayView.findViewById(R.id.progressBar).setVisibility(bl ? View.VISIBLE : View.GONE);
    	tomorrowView.findViewById(R.id.progressBar).setVisibility(bl ? View.VISIBLE : View.GONE);
    	acquiredView.findViewById(R.id.progressBar).setVisibility(bl ? View.VISIBLE : View.GONE);
    }
}